<?php 

/*****************************************************************************
 * 
 *  Copyright 2009 Sylvain Dudoit (contact : sylvain.dudoit at gmail.com)
 *  
 *  This file is part of Poupitchi.
 *
 *  Poupitchi is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Poupitchi is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Poupitchi.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/


/**    
 * Add a new message
 * 
 * @param $message
 * @return unknown_type
 */
function addMessage(&$message) {
    global $P_DATA;
    global $P_USER;
    if (trim($message['body']) != "") {
    		$message['login'] = $P_USER;
        $message['title'] = secstr($message['title']);
        $message['body'] = secstr($message['body']);
        // write
        $filename = $P_DATA."messages/".getFileName($message['login']);
        if (!file_put_contents($filename, serializeWithMask($message))) {
          sError(tr("Can't save message in file !"));
        }
    } else {
      sError(tr("Message body is empty !"));
    }
}

/**
 * Remove a message
 * 
 * @param $login
 * @return unknown_type
 */
function removeMessage($file) {
    global $P_DATA;
    global $P_ADMIN;
    if ($P_ADMIN) {
	    if (checkFilename($file)) {
		    if (!unlink($P_DATA."/messages/".$file)) {
		      sError(tr("Can't remove message file !"));
		    }
		  } else {
		  	sError(tr("Invalid file name : ").$file."!");	  	
		  }
    } else {
    	sError(tr("Action not allowed !"));
    }
}

/**
 * Count the number of messages
 * 
 * @return unknown_type
 */
function countMessages() {
    return count(getMessages());
}

/**
 * Get a messages list
 * 
 * @param $number
 * @param $start
 * @return unknown_type
 */
function getMessages($number=-1, $start=0) {
    global $P_DATA;
    $messages = array();
    $filenames = getDirList($P_DATA."messages/", $number, $start);
    foreach ($filenames as $filename) {
        $message = unserializeWithMask(file_get_contents($P_DATA."/messages/".$filename));
        $message['id'] = $filename;
        $message['login'] = substr($filename, 20, -4);
        $message['date'] = @mktime(substr($filename, 11, 2), substr($filename, 14, 2), 
            substr($filename, 17, 2), substr($filename, 5, 2), substr($filename, 8, 2), 
            substr($filename, 0, 4));
        $messages[] = $message;
    }
    return $messages;
}

?>